<template>
  <div class="data-dictionary">
    <h3>数据字典</h3>
    
    <!-- 搜索框 -->
    <div class="search-box">
      <a-input-search
        v-model:value.trim="searchText"
        placeholder="请输入字段名或描述进行搜索"
        style="width: 300px; margin-bottom: 16px;"
        @search="onSearch"
      />
    </div>
    
    <!-- 数据字典表格 -->
    <a-table
      :dataSource="paginatedData"
      :columns="columns"
      :pagination="false"
      :scroll="{ y: 400 }"
      :rowKey="(record) => record.key"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'sourceType'">
          <span :class="record.sourceType === '请求参数' ? 'request-type' : 'response-type'">
            {{ record.sourceType }}
          </span>
        </template>
      </template>
    </a-table>
    
    <!-- 分页 -->
    <div class="pagination">
      <a-pagination
        v-model:current="currentPage"
        v-model:pageSize="pageSize"
        :total="filteredData.length"
        show-size-changer
        :show-quick-jumper="true"
        :show-total="(total) => `共 ${total} 条记录`"
        @change="handlePageChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, inject, watch, computed } from 'vue'

// 从父组件注入apiState
const apiState = inject('apiState')

// 数据定义
const swaggerData = ref(null)
const searchText = ref('')
const currentPage = ref(1)
const pageSize = ref(10)

// 表格列定义
const columns = [
  {
    title: '字段',
    dataIndex: 'field',
    key: 'field',
    width: '20%'
  },
  {
    title: '字段描述',
    dataIndex: 'description',
    key: 'description',
    width: '20%'
  },
  {
    title: '字段来源',
    dataIndex: 'sourceType',
    key: 'sourceType',
    width: '15%'
  },
  {
    title: '来源接口',
    dataIndex: 'sourceApi',
    key: 'sourceApi',
    width: '25%'
  },
  {
    title: '所属模块',
    dataIndex: 'module',
    key: 'module',
    width: '20%'
  }
]

// 提取的数据字典
const dictionaryData = ref([])

// 监听apiState数据变化
watch(() => apiState.data, (value) => {
  swaggerData.value = value
  loadApiDocs(value)
}, {
  immediate: true
})

// 加载API文档并提取数据字典
function loadApiDocs(data) {
  if (!data || !data.paths || !data.components) return
  
  const result = []
  let key = 1
  
  // 遍历所有路径
  Object.keys(data.paths).forEach(path => {
    const pathItem = data.paths[path]
    
    // 遍历所有方法
    Object.keys(pathItem).forEach(method => {
      const operation = pathItem[method]
      const tag = (operation.tags && operation.tags[0]) || '默认模块'
      const summary = operation.summary || ''
      
      // 处理请求参数
      if (operation.parameters) {
        operation.parameters.forEach(param => {
          result.push({
            key: `${key++}`,
            field: param.name || '',
            description: param.description || param.title || '',
            sourceType: '请求参数',
            sourceApi: `${method.toUpperCase()} ${path} ${summary}`,
            module: tag
          })
        })
      }
      
      // 处理请求体参数
      if (operation.requestBody) {
        const content = operation.requestBody.content
        if (content) {
          Object.keys(content).forEach(contentType => {
            const schema = content[contentType].schema
            if (schema && schema.$ref) {
              const refName = schema.$ref.replace('#/components/schemas/', '')
              const schemaDefinition = data.components.schemas[refName]
              if (schemaDefinition && schemaDefinition.properties) {
                extractProperties(schemaDefinition.properties, refName, '', result, key, {
                  sourceType: '请求参数',
                  sourceApi: `${method.toUpperCase()} ${path} ${summary}`,
                  module: tag
                })
                key = result.length + 1
              }
            }
          })
        }
      }
      
      // 处理响应参数
      if (operation.responses) {
        Object.keys(operation.responses).forEach(responseCode => {
          const response = operation.responses[responseCode]
          if (response.content) {
            Object.keys(response.content).forEach(contentType => {
              const schema = response.content[contentType].schema
              if (schema && schema.$ref) {
                const refName = schema.$ref.replace('#/components/schemas/', '')
                const schemaDefinition = data.components.schemas[refName]
                if (schemaDefinition && schemaDefinition.properties) {
                  extractProperties(schemaDefinition.properties, refName, '', result, key, {
                    sourceType: '响应参数',
                    sourceApi: `${method.toUpperCase()} ${path} ${summary}`,
                    module: tag
                  })
                  key = result.length + 1
                }
              }
            })
          }
        })
      }
    })
  })
  
  dictionaryData.value = result
}

// 递归提取属性
function extractProperties(properties, parentName, prefix, result, key, info) {
  Object.keys(properties).forEach(propName => {
    const prop = properties[propName]
    const fullName = prefix ? `${prefix}.${propName}` : propName
    
    result.push({
      key: `${key++}`,
      field: fullName,
      description: prop.description || prop.title || '',
      sourceType: info.sourceType,
      sourceApi: info.sourceApi,
      module: info.module
    })
    
    // 如果属性是对象类型且有properties，则递归处理
    if (prop.type === 'object' && prop.properties) {
      extractProperties(prop.properties, propName, fullName, result, key, info)
    }
    
    // 如果属性是数组类型且有items，则处理items
    if (prop.type === 'array' && prop.items && prop.items.properties) {
      extractProperties(prop.items.properties, propName, fullName, result, key, info)
    }
  })
}

// 搜索过滤后的数据
const filteredData = computed(() => {
  if (!searchText.value) {
    return dictionaryData.value
  }
  
  const search = searchText.value.toLowerCase()
  return dictionaryData.value.filter(item => 
    (item.field && item.field.toLowerCase().includes(search)) ||
    (item.description && item.description.toLowerCase().includes(search))
  )
})

// 分页数据
const paginatedData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredData.value.slice(start, end)
})

// 搜索处理
function onSearch() {
  currentPage.value = 1
}

// 分页处理
function handlePageChange(page, size) {
  currentPage.value = page
  pageSize.value = size
}

// 重置分页
function resetPagination() {
  currentPage.value = 1
}

// 监听搜索文本变化
watch(searchText, () => {
  resetPagination()
})
</script>

<style scoped>
.data-dictionary {
  padding: 20px;
}

.search-box {
  display: flex;
  justify-content: flex-start;
  margin-bottom: 16px;
}

.pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
}

.request-type {
  color: #1890ff;
  font-weight: bold;
}

.response-type {
  color: #52c41a;
  font-weight: bold;
}
</style>